package rm

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/core/router"
)

var _irisParty iris.Party
var _irisRouters = make([]*router.Route, 0)
var IrisRouterMap = make(map[string]Router)

type RouterGrp struct {
	Description string `json:"description"`
}
type Router struct {
	Path        string `json:"path"`
	Description string `json:"description"`
	SaveOp      bool   `json:"saveOp"`
}

var _routers = make(map[RouterGrp][]Router, 0)

type HttpMethod int

const (
	GET HttpMethod = iota + 1
	POST
	PUT
	DELETE
)

func InitRouter(r iris.Party) {
	_irisParty = r
}

func GetRouterSelectOptions() interface{} {
	type option = struct {
		Value string `json:"value"`
		Desc  string `json:"desc"`
	}
	type group struct {
		Desc    string   `json:"desc"`
		Options []option `json:"options"`
	}
	result := make([]group, 0)
	for grp, routers := range _routers {
		g := group{
			Desc:    grp.Description,
			Options: make([]option, 0),
		}
		for _, r := range routers {
			g.Options = append(g.Options, option{
				Value: r.Path,
				Desc:  r.Description,
			})
		}
		result = append(result, g)
	}
	return result
}

func GetRouterList() []string {
	list := make([]string, 0)
	for _, routers := range _routers {
		for _, r := range routers {
			list = append(list, r.Path)
		}
	}
	return list
}

func BuildGrp(name, description string) (RouterGrp, router.Party) {
	grp := RouterGrp{
		Description: description,
	}
	_routers[grp] = make([]Router, 0)
	return grp, _irisParty.Party(name)
}

func AddRouter(grp RouterGrp, party router.Party, method HttpMethod, path, description string, saveOp bool, handlers ...context.Handler) *router.Route {
	var r *router.Route
	if GET == method {
		r = party.Get(path, handlers...)
	} else if POST == method {
		r = party.Post(path, handlers...)
	} else if PUT == method {
		r = party.Put(path, handlers...)
	} else if DELETE == method {
		r = party.Delete(path, handlers...)
	}
	r.Description = description
	lr := Router{
		Path:        r.Name,
		Description: description,
		SaveOp:      saveOp,
	}
	_routers[grp] = append(_routers[grp], lr)
	_irisRouters = append(_irisRouters, r)
	IrisRouterMap[r.Name] = lr
	return r
}
